define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxMiddleResult";

    var fxMiddleResultFormHtml = sysPath + "/views/fxMiddleResultForm.html";
    var getFxMiddleResultController = function () {
        return getServer() + "/fxMiddleResults";
    };
    var getFxVulnerabilityProvinceController = function () {
        return getServer() + "/fx/fxVulnerabilityProvinces";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initProvinceSelect("山东省", "日照市", "岚山区");
        initEarthquakeIntensitySelect();
        initDamageDegreeSelect();
        //createFxMiddleResultGrid();
    };

    var initProvinceSelect = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(Area);
                                    // 列表
                                    createFxMiddleResultGrid();
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(Area);

                                                    createFxMiddleResultGrid();
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(Province);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };
    var initEarthquakeIntensitySelect = function () {
        $.ajax({
            url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "earthquakeIntensity",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("earthquakeIntensitySelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initDamageDegreeSelect = function () {
        $.ajax({
            url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "damageDegree",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("damageDegreeSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initEarthquakeIntensitySelectFrom = function () {
        $.ajax({
            url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "earthquakeIntensity",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("earthquakeIntensity");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initDamageDegreeSelectFrom = function () {
        $.ajax({
            url: getFxVulnerabilityProvinceController() + "/getValidDictItemsByDictCode/" + "damageDegree",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("damageDegree");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            if ($("#provinceSelect").val() == null) {
                Util.alert("请选择省");
                return;
            }
            if ($("#citySelect").val() == null) {
                Util.alert("请选择市");
                return;
            }
            if ($("#areaSelect").val() == null) {
                Util.alert("请选择区（县）");
                return;
            }
            createFxMiddleResultGrid();
        });
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            initProvinceSelect("山东省", "日照市", "岚山区");
            $("#earthquakeIntensitySelect").val("");
            $("#damageDegreeSelect").val("");
        });
    };
    var createFxMiddleResultGrid = function () {
        $("#fxMiddleResultGrid").datagrid({
            url: getFxMiddleResultController() + "/getFxMiddleResults",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {
                    field: 'province',
                    title: '省',
                    width: '18%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '18%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '18%',
                    align: 'center'
                },
                {
                    field: 'earthquakeIntensity',
                    title: '地震动强度',
                    width: '10%',
                    align: 'center',
                    formatter: function (value) {
                        if (value == "6") {
                            return 'VI';
                        } else if (value == "7") {
                            return 'VII';
                        } else if (value == "8") {
                            return 'VIII';
                        } else if (value == "9") {
                            return 'IX';
                        } else if (value == "10") {
                            return 'X';
                        }
                    }
                },
                {
                    field: 'damageDegree',
                    title: '破坏程度',
                    width: '15%',
                    align: 'center',
                    formatter: function (value, rowData) {
                        var damageDegree = value;
                        if (value == "0") {
                            damageDegree = '基本完好';
                        } else if (value == "1") {
                            damageDegree = '轻微破坏';
                        } else if (value == "2") {
                            damageDegree = '中等破坏';
                        } else if (value == "3") {
                            damageDegree = '严重破坏';
                        } else if (value == "4") {
                            damageDegree = '完全破坏';
                        }
                        //return '<a href="#" onclick="_editFxMiddleResult(\'' + rowData.id + '\');"> ' + damageDegree + ' </a> '
                        return damageDegree;
                    }
                },
                {
                    field: 'calculatedValue',
                    title: '计算值',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'correctedValue',
                    title: '修正值',
                    width: '11%',
                    align: 'center',
                    editor: {
                            type: 'numberbox',
                            options:{precision: 2}
                            },
                },
                /*{
                    field:'probability',
                    title:'概率（系统计算值）',
                    width:'13%',
                    align:'center',
                },*/
            ]],
            toolbar: [/*{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addFxMiddleResult();
                }
            },*/ {
                iconCls: 'fa fa-plus-circle',
                text: "导出模板",
                handler: function () {
                    exportMiddleResultTemplet();
                }
            }, {
                iconCls: 'fa fa-plus-circle',
                text: "导入",
                handler: function () {
                    importMiddleResult();
                }
            }, {
                iconCls: 'fa fa-plus-circle',
                text: "导出",
                handler: function () {
                    exportMiddleResult();
                }
            }, /*{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxMiddleResult();
                }
            }*/],
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                earthquakeIntensity: $("#earthquakeIntensitySelect").val(),
                damageDegree: $("#damageDegreeSelect").val(),
            },
            onClickCell: function (index, field, value) {
                if (endEditing()) {
                    $('#fxMiddleResultGrid').datagrid('selectRow', index).datagrid('editCell', {
                        index: index,
                        field: field
                    });
                    editIndex = index;
                    mergeCells("fxMiddleResultGrid", "province,city,area,earthquakeIntensity");
                }
            },
            onAfterEdit: function (index, row, changes) {
                $.ajax({
                    url: getFxMiddleResultController(),
                    contentType: "application/json",
                    data: JSON.stringify(row),
                    type: "put",
                    success: function (data) {
                        Util.alert(data.message);
                        createFxMiddleResultGrid();
                    }
                });

            },
            onLoadSuccess: function (data) {
                //垂直合并单元格
                mergeCells("fxMiddleResultGrid", "province,city,area,earthquakeIntensity");
            },
            /*pagination: true,
            pageSize: 10*/
        });
    };
    $.extend($.fn.datagrid.methods, {
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat(
                    $(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });
    var editIndex = undefined;

    //结束编辑
    function endEditing() {
        if (editIndex == undefined) {
            return true
        }
        if ($('#fxMiddleResultGrid').datagrid('validateRow', editIndex)) {
            $('#fxMiddleResultGrid').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };

    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };
    var formValidator = function () {
        $("#fxMiddleResultForm").validate({
            rules: {
                province: {
                    required: true,
                },
                city: {
                    required: true,
                },
                area: {
                    required: true,
                },
                earthquakeIntensity: {
                    required: true,
                },
                damageDegree: {
                    required: true,
                },
            },
            messages: {
                province: {
                    required: "省不允许为空!",
                },
                city: {
                    required: "市不允许为空!",
                },
                area: {
                    required: "区/县不允许为空!",
                },
                earthquakeIntensity: {
                    required: "地震动强度不允许为空!",
                },
                damageDegree: {
                    required: "破坏程度不允许为空!",
                },
            }
        });
    };
    var getFxMiddleResult = function (id) {
        $.ajax({
            url: getFxMiddleResultController() + "/" + id,
            type: "get",
            success: function (data) {
                editProvince(data.province, data.city, data.area);
                Tool.deserialize("fxMiddleResultForm", data);
            }
        });
    };
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
    var addFxMiddleResult = function () {
        var slidebar = Util.slidebar({
            url: fxMiddleResultFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                initcreateProvince();
                initEarthquakeIntensitySelectFrom();
                initDamageDegreeSelectFrom();
                formValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#fxMiddleResultForm").valid()) {
                        var data = Tool.serialize("fxMiddleResultForm");
                        $.ajax({
                            url: getFxMiddleResultController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxMiddleResultGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    window._editFxMiddleResult = function (fxMiddleResultId) {
        var slidebar = Util.slidebar({
            url: fxMiddleResultFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                //initEarthquakeIntensitySelectFrom();
                //initDamageDegreeSelectFrom();
                formValidator();
                getFxMiddleResult(fxMiddleResultId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxMiddleResultForm").valid()) {
                        var data = Tool.serialize("fxMiddleResultForm");
                        $.ajax({
                            url: getFxMiddleResultController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxMiddleResultGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteFxMiddleResult = function () {
        var rows = $("#fxMiddleResultGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxMiddleResultController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxMiddleResultGrid();
                }
            });
        }, function () {
            return;
        });

    };

    var exportMiddleResultTemplet = function () {
        window.location.href = getServer() + "/excel/中间结果数据信息模板.xlsx";
    }
    var exportMiddleResult = function () {
        let province = $("#provinceSelect").val();
        let city = $("#citySelect").val();
        let area = $("#areaSelect").val();
        let eqIntensity = $("#earthquakeIntensitySelect").val();
        let damageDegree = $("#damageDegreeSelect").val();
        window.location.href = getFxMiddleResultController() + "/export?province=" + province + "&city=" + city + "&area=" + area +
            "&earthquakeIntensity= " + eqIntensity + " &damageDegree=" + damageDegree;
    };

    /**
     * 导入
     */
    var importMiddleResult = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/中间结果数据信息模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxMiddleResultController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                }
            });
        });
    };

    return {
        init: init
    };
});
